
import 'package:baselib/utils/keyboard_util.dart';
import 'package:baselib/utils/load_util.dart';
import 'package:baselib/utils/log_util.dart';
import 'package:baselib/utils/md5_util.dart';
import 'package:baselib/utils/navigator_util.dart';
import 'package:baselib/utils/toast_util.dart';
import 'package:baselib/widgets/comm_message_gradient_dialog.dart';
import 'package:baselib/widgets/dialog_util.dart';
import 'package:baselib/widgets/refresh_util.dart';
import 'package:flutter/material.dart';
import 'package:framelib/base/base_view_model.dart';
import 'package:framelib/config/api_config.dart';
import 'package:framelib/config/route_config.dart';
import 'package:framelib/net/baseentity.dart';
import 'package:framelib/utils/color_util.dart';
import 'package:framelib/utils/drawable_util.dart';
import 'package:framelib/utils/nim_sdk_util.dart';
import 'package:framelib/utils/string_util.dart';
import 'package:framelib/widgets/chat_room_oper_widget.dart';
import 'package:framelib/widgets/page_widget.dart';
import 'package:get/state_manager.dart';
import 'package:get/get.dart';
import 'package:module_business/module_chat/model/gift_entity.dart';
import 'package:module_business/module_comm/model/user_entity.dart';
import 'package:module_business/module_comm/model/user_params_model.dart';
import 'package:module_business/module_comm/service/module_comm_service.dart';
import 'package:module_business/module_contact/viewmodel/chat_room_view_model.dart';
import 'package:module_business/module_index/service/module_index_service.dart';
import 'package:module_business/module_my/model/func_model.dart';
import 'package:module_business/module_my/service/module_my_service.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

class OtherPersonHomeViewModel extends BaseViewModel<ModuleMyService>{

  ModuleMyService moduleMyService;
  RefreshController refreshController = RefreshController(initialRefresh: true);
  RefreshState loadStatus=RefreshState.OK;
  String userId;
  bool isFromOnlyChatRoom;
  int page = 1;
  bool isCanMoreData = false;
  List<dynamic> dataLists=[];
  //功能列表
  List<FuncModel> funcModels = [];
  UserEntity myInfo = UserEntity();
  //礼物列表
  List<GiftEntity> giftsDatas = [];

  @override
  ModuleMyService createService() =>moduleMyService = ModuleMyService();
  @override
  void onInit() {
    LogUtil.d('MyViewModel-->onInit');
    super.onInit();
    Map<String,dynamic> arguments = Get.arguments??{};
    userId =  arguments['userId'];
    isFromOnlyChatRoom =  arguments['isFromOnlyChatRoom']??false;
    //设置初始化数据
    setInitData();
    //获取优化礼物墙
    // getPersonGiftsWall();
    //获取黑名单
    getMyBlacks();
    //获取关注的人员列表
    getFollows();
  }
  setInitData(){
    funcModels=[
      FuncModel(preImgPath: DrawableUtil.instance.icon_person_my_collection,title: StringUtil.instance.My_collection),
      FuncModel(preImgPath: DrawableUtil.instance.icon_person_administrator_room,title: StringUtil.instance.as_Administrator),
      FuncModel(preImgPath: DrawableUtil.instance.icon_person_browse_records,title: StringUtil.instance.Browse_Records),
      FuncModel(preImgPath: DrawableUtil.instance.icon_person_user_agreement,title: StringUtil.instance.User_Agreement),
      FuncModel(preImgPath: DrawableUtil.instance.icon_person_privacy_agreement,title: StringUtil.instance.Privacy_Agreement),
    ];
  }

  onRefresh({int pageCur,}) async{
    Map<String,dynamic> upData={
      "searchValue": userId
    };
    BaseEntity baseEntity = await moduleMyService.api_user_querySimpleUserById(parmsMap: upData);
    if(refreshController!=null)refreshController.refreshCompleted();
    if(refreshController!=null)refreshController.loadComplete();
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      myInfo = baseEntity?.result??UserEntity();
      // var giftsJson = [
      //   {
      //     "id": 3,
      //     "createTime": 1654503761000,
      //     "updateTime": 1683518116000,
      //     "valid": 1,
      //     "giftImg": "https://app-bucket-test.oss-accelerate.aliyuncs.com/document/gift/1542709777065312256.png",
      //     "giftName": "red rose",
      //     "giftPrice": 10,
      //     "giftSmallImg": "https://app-bucket-test.oss-accelerate.aliyuncs.com/document/gift/1544608318524227584.png",
      //     "giftType": 1,
      //     "convertGoldAmount": 10,
      //     "giftModule": 2,
      //     "roomFloatingScreenFlag": 0,
      //     "serviceFloatingScreenFlag": 0,
      //     "backpackGiftNum": 0
      //   },
      //   {
      //     "id": 30,
      //     "createTime": 1656928280000,
      //     "updateTime": 1657194082000,
      //     "valid": 1,
      //     "giftImg": "https://app-bucket-test.oss-accelerate.aliyuncs.com/document/gift/1543895107218964480.png",
      //     "giftName": "藍玫瑰",
      //     "giftPrice": 10,
      //     "giftSmallImg": "https://app-bucket-test.oss-accelerate.aliyuncs.com/document/gift/1543895129436192768.png",
      //     "giftType": 1,
      //     "convertGoldAmount": 10,
      //     "giftModule": 1,
      //     "roomFloatingScreenFlag": 0,
      //     "serviceFloatingScreenFlag": 0,
      //     "backpackGiftNum": 0
      //   },
      //   {
      //     "id": 4,
      //     "createTime": 1655351139000,
      //     "updateTime": 1683711295000,
      //     "valid": 1,
      //     "giftImg": "https://app-bucket-test.oss-accelerate.aliyuncs.com/document/gift/1542709855687540736.png",
      //     "giftName": "lollipop",
      //     "giftPrice": 100,
      //     "giftSmallImg": "https://app-bucket-test.oss-accelerate.aliyuncs.com/document/gift/1544608371733168128.png",
      //     "giftType": 1,
      //     "convertGoldAmount": 100,
      //     "giftModule": 2,
      //     "roomFloatingScreenFlag": 0,
      //     "serviceFloatingScreenFlag": 0,
      //     "backpackGiftNum": 0
      //   },
      //   {
      //     "id": 55,
      //     "createTime": 1657098452000,
      //     "updateTime": null,
      //     "valid": 1,
      //     "giftImg": "https://app-bucket-test.oss-accelerate.aliyuncs.com/document/gift/1544608809811443712.svga",
      //     "giftName": "彩虹雪糕",
      //     "giftPrice": 100,
      //     "giftSmallImg": "https://app-bucket-test.oss-accelerate.aliyuncs.com/document/gift/1544608564746649600.png",
      //     "giftType": 3,
      //     "convertGoldAmount": 100,
      //     "giftModule": 1,
      //     "roomFloatingScreenFlag": 0,
      //     "serviceFloatingScreenFlag": 0,
      //     "backpackGiftNum": 0
      //   },
      //   {
      //     "id": 54,
      //     "createTime": 1657091294000,
      //     "updateTime": null,
      //     "valid": 1,
      //     "giftImg": "https://app-bucket-test.oss-accelerate.aliyuncs.com/document/gift/1544578836023214080.svga",
      //     "giftName": "棒棒糖",
      //     "giftPrice": 300,
      //     "giftSmallImg": "https://app-bucket-test.oss-accelerate.aliyuncs.com/document/gift/1544578452085014528.png",
      //     "giftType": 3,
      //     "convertGoldAmount": 300,
      //     "giftModule": 1,
      //     "roomFloatingScreenFlag": 0,
      //     "serviceFloatingScreenFlag": 0,
      //     "backpackGiftNum": 0
      //   },
      //   {
      //     "id": 38,
      //     "createTime": 1657024624000,
      //     "updateTime": 1657090569000,
      //     "valid": 1,
      //     "giftImg": "https://app-bucket-test.oss-accelerate.aliyuncs.com/document/gift/1544299253524856832.svga",
      //     "giftName": "项链",
      //     "giftPrice": 520,
      //     "giftSmallImg": "https://app-bucket-test.oss-accelerate.aliyuncs.com/document/gift/1544575904389267456.png",
      //     "giftType": 3,
      //     "convertGoldAmount": 520,
      //     "giftModule": 1,
      //     "roomFloatingScreenFlag": 0,
      //     "serviceFloatingScreenFlag": 0,
      //     "backpackGiftNum": 0
      //   },
      //   {
      //     "id": 7,
      //     "createTime": 1655351564000,
      //     "updateTime": 1683711313000,
      //     "valid": 1,
      //     "giftImg": "https://app-bucket-test.oss-accelerate.aliyuncs.com/document/gift/1544610988341329920.png",
      //     "giftName": "Teddy Bear",
      //     "giftPrice": 660,
      //     "giftSmallImg": "https://app-bucket-test.oss-accelerate.aliyuncs.com/document/gift/1544610972939845632.png",
      //     "giftType": 1,
      //     "convertGoldAmount": 660,
      //     "giftModule": 2,
      //     "roomFloatingScreenFlag": 0,
      //     "serviceFloatingScreenFlag": 0,
      //     "backpackGiftNum": 0
      //   },
      //   {
      //     "id": 37,
      //     "createTime": 1657024516000,
      //     "updateTime": 1657090576000,
      //     "valid": 1,
      //     "giftImg": "https://app-bucket-test.oss-accelerate.aliyuncs.com/document/gift/1544298636995723264.svga",
      //     "giftName": "調皮炸彈",
      //     "giftPrice": 1000,
      //     "giftSmallImg": "https://app-bucket-test.oss-accelerate.aliyuncs.com/document/gift/1544575938467987456.png",
      //     "giftType": 3,
      //     "convertGoldAmount": 1000,
      //     "giftModule": 1,
      //     "roomFloatingScreenFlag": 0,
      //     "serviceFloatingScreenFlag": 0,
      //     "backpackGiftNum": 0
      //   },
      //   {
      //     "id": 39,
      //     "createTime": 1657024764000,
      //     "updateTime": 1657096681000,
      //     "valid": 1,
      //     "giftImg": "https://app-bucket-test.oss-accelerate.aliyuncs.com/document/gift/1544299499436900352.svga",
      //     "giftName": "钻戒",
      //     "giftPrice": 1314,
      //     "giftSmallImg": "https://app-bucket-test.oss-accelerate.aliyuncs.com/document/gift/1544575882394337280.png",
      //     "giftType": 3,
      //     "convertGoldAmount": 1314,
      //     "giftModule": 1,
      //     "roomFloatingScreenFlag": 1,
      //     "serviceFloatingScreenFlag": 0,
      //     "backpackGiftNum": 0
      //   }
      // ];
      // giftsJson.forEach((element) {
      //   giftsDatas.add(GiftEntity.fromJson(element));
      // });
      update();
    }
  }

  void startDeleteAccount() async{
    LoadUtil.showLoad(loadingText: StringUtil.instance.submiting);
    Map<String,dynamic> parmsMap= {};
    BaseEntity baseEntity = await moduleMyService.api_user_deleteAccount(parmsMap: parmsMap);
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      await NIMSDKUtil.instance.logout();
      await UserParamsModel.instance.clear();
      LoadUtil.hideLoad();
      ToastUtil.toast(StringUtil.instance.Delete_account_success);
      NavigatorUtil.offAllByName(RouteConfig.loginPage);
    }else{
      LoadUtil.hideLoad();
      ToastUtil.toast(baseEntity?.message);
    }
  }

  void getPersonGiftsWall() async{
    Map<String,dynamic> upData={
      "searchValue": userId,
    };
    BaseEntity baseEntity = await moduleMyService.api_voicechat_gift_giftWall(parmsMap: upData);
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      giftsDatas = baseEntity?.result??[];
    }
    update();
  }
  //查询我的拉黑用户列表
  void getMyBlacks() async{
    Map<String,dynamic> upData={
      "currentPage":1,
      "pageSize":100000,
    };
    UserParamsModel.instance.setMyBlackIds([]);
    BaseEntity baseEntity = await moduleMyService.api_user_blackList(parmsMap: upData);
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      List<UserEntity> myBlackTemps = baseEntity?.result??[];
      if(myBlackTemps.isNotEmpty){
        var myBlackIds = myBlackTemps.map((e) => '${e?.userId}').toList();
        LogUtil.d('getMyBlacks--->myBlackIds=$myBlackIds');
        UserParamsModel.instance.setMyBlackIds(myBlackIds);
      }
    }
    update();
  }
  bool isInBlackList() {
    return UserParamsModel.instance.myBlackIds.contains('${userId??('-1000')}');
  }
  bool isInFollows() {
    return UserParamsModel.instance.myFollowIds.contains('${userId??('-1000')}');
  }
  popPoint() {
    showModalBottomSheet(
        context: Get.context,
        isScrollControlled: true,
        backgroundColor: ColorUtil.instance.color_transparent,
        builder: (BuildContext context){
          return ChatRoomOperWidget(
            isInBlackList: isInBlackList(),
            reportSelectedFunc: (){
              LogUtil.d('showChatRoomOper--->举报聊天室');
              startReport();
            },
            blackSelectedFunc: (){
              startBlack();
            },
          );
        }
    );
  }

  void startReport() {
    // LoadUtil.showLoad(loadingText: '${StringUtil.instance.submiting}...');
    // Future.delayed(Duration(milliseconds: 500), ()=>LoadUtil.hideLoad());
    // ToastUtil.toast(StringUtil.instance.Report_Success);
    NavigatorUtil.pushByName(RouteConfig.reportPage,arguments: {
      'beBlockUid': '${userId}'
    });
  }
  //拉黑
  void startBlack() async{
    LoadUtil.showLoad(loadingText: '${StringUtil.instance.submiting}...');
    Map<String,dynamic> upData={
      "type": 1,
      "userId": userId,
      "yxAccid": myInfo?.yxAccid
    };
    BaseEntity baseEntity = await moduleMyService.api_user_BlackOrRemove(parmsMap: upData,
        isBlack: !isInBlackList());
    LoadUtil.hideLoad();
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      //查询我的拉黑用户列表
      getMyBlacks();
    }else{
      ToastUtil.toast(baseEntity?.message);
    }
  }
  doFollow() async {
    LoadUtil.showLoad(loadingText: '${StringUtil.instance.submiting}...');
    Map<String,dynamic> upData={
      "followUserId": userId
    };
    //动作类型（1：关注，2：取消关注，3：拉黑用户）
    if(isInFollows()){
      upData['followType']=2;
    }else{
      upData['followType']=1;
    }
    BaseEntity baseEntity = await moduleMyService.api_user_followUser(parmsMap: upData);
    LoadUtil.hideLoad();
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      getFollows();
      if(isFromOnlyChatRoom??false){
        ChatRoomViewModel chatRoomViewModel = Get.find();
        if(chatRoomViewModel!=null)chatRoomViewModel.getMyFollows();
      }
    }else{
      ToastUtil.toast(baseEntity?.message);
    }
  }

  //获取关注人员列表
  getFollows()async{
    Map<String,dynamic> upData={
      'currentPage': 1,
      'pageSize': 100000,
      "type":3,
    };
    UserParamsModel.instance.setMyFollowIds([]);
    BaseEntity baseEntity= await moduleMyService.api_user_userFriend(parmsMap: upData);
    if(refreshController!=null)refreshController.refreshCompleted();
    if(refreshController!=null)refreshController.loadComplete();
    if(baseEntity?.code==ApiConfig.SUCCESS_CODE){
      List<UserEntity> dataTemp=baseEntity?.result??[];
      var myFollowIds = dataTemp.map((e) => '${e?.userId}').toList();
      LogUtil.d('getMyFollowIds--->myFollowIds=$myFollowIds');
      UserParamsModel.instance.setMyFollowIds(myFollowIds);
    }
    update();
  }

  isMySelf() {
    return '${UserParamsModel.instance.userId}'==userId;
  }

}
